package com.qianseit.westore.activity.account;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.qianseit.westore.AgentApplication;
import com.qianseit.westore.BaseDoFragment;
import com.qianseit.westore.Run;
import com.qianseit.westore.activity.AgentActivity;
import com.qianseit.westore.http.JsonRequestBean;
import com.qianseit.westore.http.JsonTask;
import com.qianseit.westore.http.JsonTaskHandler;
import com.qianseit.westore.ui.CircleFlowIndicator;
import com.qianseit.westore.ui.FlowScrollView;
import com.qianseit.westore.ui.FlowView;
import com.qianseit.westore.util.loader.VolleyImageLoader;
import com.beautymiracle.androidclient.R;

public class ShopServiceFragment extends BaseDoFragment {

	private final static int INTERVAL_AUTO_SNAP_FLOWVIEW = 5000;
	
	private EditText mCardNum;
	private ImageView mSearchBtn;
	private FlowView mTopAdsView;
	private VolleyImageLoader mVolleyImageLoader;
	private Point mScreenSize;
	private ImageView mDefaultTopAdsView;
	
	private ArrayList<JSONObject> mTopAdsArray = new ArrayList<JSONObject>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActionBar.setTitle(R.string.me_item_shop);
		mScreenSize = Run.getScreenSize(mActivity.getWindowManager());
		mVolleyImageLoader = ((AgentApplication) mActivity.getApplication())
				.getImageLoader();
	}
	
	@Override
	public void init(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_shop_service, null);
		getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		mCardNum = (EditText) rootView.findViewById(R.id.fragment_shop_service_carnumber);
		mSearchBtn = (ImageView) rootView.findViewById(R.id.fragment_shop_service_searchBtn);
		mSearchBtn.setOnClickListener(this);
		mTopAdsView = (FlowView) rootView.findViewById(R.id.fragment_shopservice_top_adsview);
		mTopAdsView.setParentScrollView((FlowScrollView)rootView.findViewById(R.id.fragment_shopservice_scrollview));
		mDefaultTopAdsView = (ImageView) rootView.findViewById(R.id.fragment_shopservice_top_adsview_default);
		new JsonTask().execute(new GetTopAds());
	}
	
	@Override
	public void onClick(View v) {
		if (v == mSearchBtn) {
			if (TextUtils.isEmpty(mCardNum.getText().toString().trim())) {
				Run.alert(mActivity, "请输入你要查询的美通卡号");
			} else {
				new JsonTask().execute(new GetCardMessage());
			}
		}else{
			super.onClick(v);
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		mHandler.sendEmptyMessageDelayed(0, INTERVAL_AUTO_SNAP_FLOWVIEW);
	}

	@Override
	public void onPause() {
		super.onPause();
		mHandler.removeMessages(0);
	}
	
	public class GetCardMessage implements JsonTaskHandler{

		@Override
		public void task_response(String json_str) {
			hideLoadingDialog_mt();
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					JSONObject data = all.optJSONObject("data");
					if (data != null) {
						findViewById(R.id.fragment_shop_service_card_layout).setVisibility(View.VISIBLE);
						((TextView) findViewById(R.id.fragment_shop_service_cardNo)).setText(
								getString(R.string.card_Num, data.optString("CardNo")));
						((TextView) findViewById(R.id.fragment_shop_service_card_statu)).setText(
								getString(R.string.card_Status,data.optString("CardStatus")));
						((TextView) findViewById(R.id.fragment_shop_service_card_balance)).setText(
								getString(R.string.card_balance,data.optString("BalanceAmt")));
						((TextView) findViewById(R.id.fragment_shop_service_card_endDate)).setText(
								getString(R.string.card_endData,data.optString("EndDate")));
					} else {
						findViewById(R.id.fragment_shop_service_card_layout).setVisibility(View.GONE);
						Run.alert(mActivity, all.optString("data"));
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public JsonRequestBean task_request() {
			showCancelableLoadingDialog();
			JsonRequestBean req = new JsonRequestBean(Run.API_URL, "mobileapi.member.mtkinfo");
			req.addParams("card_no", mCardNum.getText().toString());
			return req;
		}
		
	}
	
	private void reloadAdsView() {
		if (mTopAdsArray != null && mTopAdsArray.size() > 0) {
			mDefaultTopAdsView.setVisibility(View.GONE);
			CircleFlowIndicator mTopAdsIndicator = (CircleFlowIndicator) rootView
					.findViewById(R.id.fragment_shopservice_top_adsview_indicator);
			mTopAdsIndicator.setVisibility(View.VISIBLE);
			mTopAdsView.setAdapter(new FlowAdapter());
			mTopAdsView.setFlowIndicator(mTopAdsIndicator);
			mTopAdsIndicator.setViewFlow(mTopAdsView);
			try {
				JSONObject topAdsObject = mTopAdsArray.get(0);

				// 根据屏幕和图片大小调整显示尺寸
				int width = topAdsObject.optInt("ad_img_w");
				int height = topAdsObject.optInt("ad_img_h");
				int viewHeight = mScreenSize.x * height / width;
				LayoutParams params = mTopAdsView.getLayoutParams();
				params.height = viewHeight;
				mTopAdsView.setLayoutParams(params);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			mDefaultTopAdsView.setVisibility(View.VISIBLE);
			rootView.findViewById(R.id.fragment_promotion_adsview_indicator)
					.setVisibility(View.GONE);
		}
	}
	
	private class FlowAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return mTopAdsArray.size();
		}

		@Override
		public JSONObject getItem(int position) {
			return mTopAdsArray.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				ImageView view = new ImageView(mActivity);
				view.setLayoutParams(new AbsListView.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
				view.setScaleType(ScaleType.CENTER_CROP);
				view.setOnClickListener(mAdViewClickListener);
				convertView = view;
			}

			JSONObject topAdsObject = getItem(position);
			convertView.setTag(R.id.tag_object, topAdsObject);
			mVolleyImageLoader.showImage((ImageView) convertView,
					topAdsObject.optString("ad_img"));
			return convertView;
		}

	}
	
	private OnClickListener mAdViewClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (v.getTag(R.id.tag_object) != null) {
				JSONObject data = (JSONObject) v.getTag(R.id.tag_object);
				String urlType = data.optString("url_type");
				if ("goods".equals(urlType)) {
					startActivity(AgentActivity.intentForFragment(mActivity,
							AgentActivity.FRAGMENT_GOODS_DETAIL).putExtra(
							Run.EXTRA_CLASS_ID, data.optString("ad_url")));
				} else if ("article".equals(urlType)) {
					startActivity(AgentActivity.intentForFragment(mActivity,
							AgentActivity.FRAGMENT_ARTICLE_READER).putExtra(
							Run.EXTRA_ARTICLE_ID, data.optString("ad_url")));
				} else if ("virtual_cat".equals(urlType)) {
					startActivity(AgentActivity
							.intentForFragment(mActivity,
									AgentActivity.FRAGMENT_GOODS_LIST)
							.putExtra(Run.EXTRA_VITUAL_CATE,
									data.optString("ad_url"))
							.putExtra(Run.EXTRA_TITLE,
									data.optString("ad_name")));
				} else if ("cat".equals(urlType)) {
					startActivity(AgentActivity
							.intentForFragment(mActivity,
									AgentActivity.FRAGMENT_GOODS_LIST)
							.putExtra(Run.EXTRA_CLASS_ID,
									data.optString("ad_url"))
							.putExtra(Run.EXTRA_TITLE,
									data.optString("ad_name")));
				}
			}
		}
	};
	
	private class GetTopAds implements JsonTaskHandler {

		@Override
		public void task_response(String json_str) {
			try {
				JSONObject all = new JSONObject(json_str);
				mTopAdsArray.clear();
				if (Run.checkRequestJson(mActivity, all)) {
					JSONArray list = all.getJSONArray("data");
					list = list.getJSONObject(0).getJSONArray("items");
					int count = (list != null) ? list.length() : 0;
					for (int i = 0; i < count; i++) {
						mTopAdsArray.add((JSONObject) list.get(i));
					}
					reloadAdsView();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public JsonRequestBean task_request() {
//			return new JsonRequestBean(Run.API_URL,
//					"mobileapi.salesgoods.get_sales_ads").addParams(
//					"ad_position", "1"); // 1:促销页面 2:商品列表页面
			return new JsonRequestBean(Run.API_URL,
					"mobileapi.salesgoods.get_sales_ads").addParams(
							"ad_type", "common")
							.addParams("ad_type_id", "shop_ad");
		}

	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (mTopAdsView.getViewsCount() > 1) {
				int count = mTopAdsView.getViewsCount();
				int curScreen = mTopAdsView.getSelectedItemPosition();
				if (curScreen >= (count - 1))
					mTopAdsView.smoothScrollToScreen(0);
				else
					mTopAdsView.smoothScrollToScreen(curScreen + 1);
			}
			mHandler.sendEmptyMessageDelayed(0, INTERVAL_AUTO_SNAP_FLOWVIEW);
		};
	};
	
}
